package com.pkk.blny.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;

/**
 * @description: redis和ehcache的配置
 * @author: peikunkun
 * @create: 2020-01-19 10:27
 **/
@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
public class CacheManagerConfig extends CachingConfigurerSupport {

  private final CacheProperties cacheProperties;

  CacheManagerConfig(CacheProperties cacheProperties) {
    this.cacheProperties = cacheProperties;
  }

  /**
   * h cacheManager名字
   */
  public interface CacheManagerNames {

    /**
     * redis
     */
    String REDIS_CACHE_MANAGER = "redisCacheManager";

    /**
     * ehCache
     */
    String EHCACHE_CACHE_MAANGER = "ehCacheCacheManager";
  }


  /**
   * 创建ehCacheCacheManager
   */
  @Bean
  @Primary
  public EhCacheCacheManager ehCacheCacheManager() {
    Resource location = this.cacheProperties.resolveConfigLocation(this.cacheProperties.getEhcache().getConfig());
    return new EhCacheCacheManager(EhCacheManagerUtils.buildCacheManager(location));
  }
}
